package com.acc.store.service.impl;

import com.acc.store.dto.CategoryDto;
import com.acc.store.entity.Category;
import com.acc.store.entity.Product;
import com.acc.store.mapper.CategoryMapper;
import com.acc.store.service.CategoryService;
import com.acc.store.vo.CategoryVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 10067
 * @description 针对表【category(分类表)】的数据库操作Service实现
 * @createDate 2023-10-13 18:04:52
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {
    @Override
    public List<CategoryVo> tree() {
        List<CategoryVo> list = query().list().stream().map(item -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(item, categoryVo);
            return categoryVo;
        }).toList();
        List<CategoryVo> all = list;
        List<CategoryVo> categoryVos = list.stream().filter(entity -> entity.getParentId() == null).map(menu -> {
            menu.setSonList(findSon(menu, all));
            return menu;
        }).toList();
        return categoryVos;
    }

    @Override
    public void saveDto(CategoryDto categoryDto) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto, category);
        save(category);
    }

    @Override
    public void delete(List<Long> ids) {
        //估计超级慢
        for (Long id : ids) {
            Long count1 = Db.lambdaQuery(Product.class).eq(Product::getCategoryId, id).count();
            Long count2 = lambdaQuery().eq(Category::getParentId, id).count();
            if ((count2 == null || count2 == 0) && (count1 == null || count1 == 0)) {
                removeById(id);
            }else {
                throw new RuntimeException("该分组不为空");
            }
        }
    }

    private List<CategoryVo> findSon(CategoryVo root, List<CategoryVo> all) {
        List<CategoryVo> leave = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentId() == root.getCategoryId();
        }).map(categoryEntity -> {
            categoryEntity.setSonList(findSon(categoryEntity, all));
            return categoryEntity;
        }).toList();
        return leave;
    }
}




